﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using Facade;
using IronOne.SalesOne.BusinessObjects;
using System.Configuration;

namespace IronOne.SalesOne.SalesOneWeb.SalesQuotations
{
    public partial class SearchSalesQuatation : SOSecurityPage, IDataPage, IntTest
    {

        StructureFacade fac = new StructureFacade();
        int userType;
        string postCause;
        private int pageNo;
        List<ProspectQuotations> quoList; 
        List<ProspectQuotations> quoList_1;
        string SOCode;
        DateTime DateFrom;
        DateTime DateTo;
        int userId;
        string plnCode=string.Empty;
        string pCode = string.Empty;
       



        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                //string postCause = this.Page.Request.Params.Get("__EVENTTARGET");


                if (!IsPostBack)
                {
                    txtFromDate.Text = System.DateTime.Today.ToShortDateString();
                    txtToDate.Text = System.DateTime.Today.ToShortDateString();


                    lblReportType.Visible = false;
                    drpDownReportType.Visible = false;
                    //CompareValidator2.Visible = false;

                    ValidateUserCredentials(Request.Url.LocalPath);

                    User user = fac.GetUser(User.Identity.Name);
                    UserInformation info = fac.GetUserInformation(User.Identity.Name);
                    userType = user.UserType;
                    userId = user.NodeId;




                    if (userType == 1)
                    {
                        FillDropDown("Branch");
                    }
                    else if (userType == 2)
                    {
                        FillDropDown("BranchGrp");
                    }
                    else if (userType == 3)
                    {
                        UserInBranch();
                    }
                    else if (userType == 4)
                    {
                        UserInUnit();
                    }

                }
            }
            catch (Exception ex) { }

        }

        //set details for branch user

        public void UserInBranch()
        {
            User user = fac.GetUser(User.Identity.Name);
            UserInformation info = fac.GetUserInformation(User.Identity.Name);
            userType = user.UserType;


            //User user = fac.GetUser(User.Identity.Name);
            //userType = user.UserType;
            FillDropDown("Branch");

            drpBranch.SelectedValue = info.NodeId.ToString();

            //drpBranch.SelectedValue = user.NodeId.ToString();
            drpBranch.Enabled = false;
            FillDropDown("Unit");
        }

        //set details for unit user

        public void UserInUnit()
        {
            User user = fac.GetUser(User.Identity.Name);
            UserInformation info = fac.GetUserInformation(User.Identity.Name);
            userType = user.UserType;


            FillDropDown("Branch");
            FillDropDown("UnitOrg");
            //User user = fac.GetUser(User.Identity.Name);
            //userType = user.UserType;
            //drpBranch.SelectedValue = fac.GetUnit(user.NodeId).BranchId.ToString();
            drpBranch.SelectedValue = info.BranchId.ToString();
            drpBranch.Enabled = false;
            drpUnit.SelectedValue = info.NodeId.ToString();
            //drpUnit.SelectedValue = user.NodeId.ToString();
            drpUnit.Enabled = false;

            FillDropDown("SOCode");

        }


        public void FillDropDown(string type)
        {
            switch (type)
            {


                case "BranchGrp":

                    List<Branch> br1 = fac.GetBranchesForGroup(userId);

                    Branch branch1 = new Branch();
                    branch1.BranchId = -1;
                    branch1.BranchName = "Select...";
                    br1.Insert(0, branch1);
                    drpBranch.DataSource = br1;
                    drpBranch.DataTextField = "BranchName";
                    drpBranch.DataValueField = "BranchId";
                    drpBranch.DataBind();

                    break;


                case "Branch":
                    List<Branch> br = fac.GetBranches("BranchName ASC");
                    Branch branch = new Branch();
                    branch.BranchId = -1;
                    branch.BranchName = "Select...";
                    br.Insert(0, branch);
                    drpBranch.DataSource = br;
                    drpBranch.DataTextField = "BranchName";
                    drpBranch.DataValueField = "BranchId";
                    drpBranch.DataBind();

                    break;

                case "Unit":
                    if (drpBranch.SelectedValue != "-1")
                    {

                        if (drpSOCode.SelectedItem.Value != "Select...")
                        {
                            List<string> soCode = new List<string>();
                            soCode.Insert(0, "Select...");
                            drpSOCode.DataSource = soCode;
                            drpSOCode.DataBind();

                            //drpSOcode.Items.Clear();
                        }


                        List<SalesOneUnit> un = fac.GetUnitsInBranch(Convert.ToInt32(drpBranch.SelectedValue));
                        SalesOneUnit unSel = new SalesOneUnit();

                        if (un.Count != 0)
                        {
                            //lblResult.Visible = false;
                            btnSearch.Enabled = true;
                            drpUnit.Enabled = true;
                            drpSOCode.Enabled = true;
                            //Image1.Visible = true;
                            //Image2.Visible = true;
                            txtFromDate.Enabled = true;
                            txtToDate.Enabled = true;


                            unSel.UnitId = -1;
                            unSel.Name = "Select...";
                            un.Insert(0, unSel);

                            drpUnit.DataSource = un;
                            drpUnit.DataTextField = "Name";
                            drpUnit.DataValueField = "UnitId";
                            drpUnit.DataBind();
                        }
                        else
                        {
                            //lblResult.Visible = true;
                            //lblResult.Text = "No more Units for this branch";
                            //lblResult.ForeColor = System.Drawing.Color.Red;

                            MassageSummery("IIS504");

                            drpUnit.Enabled = false;
                            drpSOCode.Enabled = false;
                            //Image7.Visible = false;
                            //Image8.Visible = false;
                            txtFromDate.Enabled = false;
                            txtToDate.Enabled = false;
                            btnSearch.Enabled = false;
                        }
                    }

                    break;

                case "UnitOrg":
                    List<SalesOneUnit> unt1 = fac.GetUnits("UnitId ASC");
                    SalesOneUnit sou = new SalesOneUnit();

                    sou.UnitId = -1;
                    sou.Name = "Select...";

                    unt1.Insert(0, sou);
                    drpUnit.DataSource = unt1;
                    drpUnit.DataTextField = "Name";
                    drpUnit.DataValueField = "UnitId";

                    drpUnit.DataBind();


                    break;

                case "SOCode":
                    if (drpUnit.SelectedValue != "-1")
                    {
                        //set the error msg using this place. 
                        List<string> socode = fac.GetSOsInUnit(Convert.ToInt32(drpUnit.SelectedValue));
                        if (socode.Count != 0)
                        {


                            btnSearch.Enabled = true;
                            //lblResult.Visible = true;
                            txtFromDate.Enabled = true;
                            txtToDate.Enabled = true;
                            drpSOCode.Enabled = true;
                            //Image7.Visible = true;
                            //Image8.Visible = true;
                            string str = "Select...";
                            socode.Insert(0, str);
                            drpSOCode.DataSource = socode;
                            drpSOCode.DataBind();

                        }
                        else
                        {
                            //lblResult.Visible = true;
                            //lblResult.Text = "No more SOCodes to this user";
                            //lblResult.ForeColor = System.Drawing.Color.Red;

                            MassageSummery("IIS504");

                            drpSOCode.Enabled = false;
                            //Image7.Visible = false;
                            //Image8.Visible = false;
                            txtFromDate.Enabled = false;
                            txtToDate.Enabled = false;
                            btnSearch.Enabled = false;
                        }

                    }
                    break;

                default:
                    break;
            }
        }

        protected void drpBranch_SelectedIndexChanged(object sender, EventArgs e)
        {
            UCGrid1.Visible = false;
            drpDownReportType.Visible = false;
            lblReportType.Visible = false;
            btnView.Visible = false;
            try
            {
                FillDropDown("Unit");
            }
            catch (Exception ex) { }
                
            }

        protected void drpUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            UCGrid1.Visible = false;
            drpDownReportType.Visible = false;
            lblReportType.Visible = false;
            btnView.Visible = false;

            try
            {
                FillDropDown("SOCode");
            }
            catch (Exception ex) { }
            }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {

                if (drpSOCode.SelectedIndex > 0)
                {

                    StructureFacade fac = new StructureFacade();
                    SOCode = drpSOCode.SelectedValue.ToString();
                    string QuoNo = txtQuotNo.Text;
                    DateFrom = Convert.ToDateTime(txtFromDate.Text);
                    DateTo = Convert.ToDateTime(txtToDate.Text);


                    #region commented
                    //if (!IsPostBack)
                    //    {
                    //        pageNo = 1;
                    //        UCGrid1.SetText("1");
                    //        unitList = Source(bId, 1);
                    //    }
                    //    else
                    //    {
                    //        unitList = Source(bId, pageNo);
                    //    } 
                    #endregion


                    if (QuoNo == "")
                    {

                        #region commented
                        //if (!IsPostBack)
                        //{
                        //    pageNo = 1;
                        //    UCGrid1.SetText("1");
                        //    SearchQuotations(SOCode, DateFrom, DateTo, 1);
                        //    //quoList = fac.GetQuotationsBySocode(soCode, fromDate, toDate,1);
                        //}
                        //else
                        //{
                        //    //quoList = fac.GetQuotationsBySocode(soCode, fromDate, toDate, pageNo);
                        //    SearchQuotations(SOCode, DateFrom, DateTo, pageNo);
                        //} 
                        #endregion

                        pageNo = 1;
                        UCGrid1.SetText("1");
                        SearchQuotations(SOCode, DateFrom, DateTo, 1);

                        LoadGrid(quoList);
                    }
                    else
                    {

                        #region commented
                        //if (!IsPostBack)
                        //{
                        //    pageNo = 1;
                        //    UCGrid1.SetText("1");
                        //    SearchQuotations_1(SOCode, QuoNo, DateFrom, DateTo, 1);
                        //    //quoList = fac.GetQuotationsBySocode(soCode, fromDate, toDate,1);
                        //}
                        //else
                        //{
                        //    //quoList = fac.GetQuotationsBySocode(soCode, fromDate, toDate, pageNo);
                        //    SearchQuotations_1(SOCode, DateFrom, DateTo, pageNo);
                        //}

                        //LoadGrid(quoList_1); 
                        #endregion


                        List<ProspectQuotations> quoList = fac.GetQuotationsByNo(SOCode, QuoNo, DateFrom, DateTo);
                        LoadGrid(quoList);

                    }
                }
                else if (drpSOCode.SelectedIndex <= 0)
                {
                    MassageSummery("IIS505");
                }

            }
            catch (Exception ex) { }

        }

        public void SearchQuotations(string soCode, DateTime fromD, DateTime toD, int pageN)
        {
            quoList = fac.GetQuotationsBySocode(soCode, fromD, toD, pageN);
            if (quoList.Count == Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]))
            {
                UCGrid1.IsLastPage = (fac.GetQuotationsBySocode(soCode, fromD, toD, pageN + 1)).Count > 0 ? false : true;
            }
        }
        //public void SearchQuotations_1(string soCode, DateTime fromD, DateTime toD, int pageN)
        //{
        //    quoList_1 = fac.GetQuotationsBySocode(soCode, fromD, toD, pageN);
        //}


        // load the grid

        private void LoadGrid(List<ProspectQuotations> pList)
        {
            if (pList.Count != 0)
            {
                //lblResult.Visible = false;
                UCGrid1.Visible = true;
               // int[] numbers = { 1, 4, 6, 8, 9, 10, 11, 12 };
                int[] numbers = { 1, 4, 6, 8, 9, 10};

                UCGrid1.styleList = new List<GridViewStyle> {
                new GridViewStyle{
                    ColumnId = "QuotationNo",
                    ColumnHeader = "Quotation No.",
                    ColumnWidth = 120},
                new GridViewStyle{
                    ColumnId = "SOCode",
                    ColumnHeader = "SO Code",
                    ColumnWidth = 80},
                new GridViewStyle{
                    ColumnId = "PlanCode",
                    ColumnHeader = "Plan Code",
                    ColumnWidth = 80},
                new GridViewStyle{
                    ColumnId = "LastUpdated",
                    ColumnHeader = "Quotation Date",
                    ColumnWidth = 130}
                 
            };




                UCGrid1.SetDataSource(pList, numbers);




                Session["quotationNum"] = ((GridViewRow)Session["firstRow"]).Cells[2].Text;
                Session["planCode"] = ((GridViewRow)Session["firstRow"]).Cells[5].Text;
                LoadDrpReport(Session["quotationNum"].ToString());


                if (plnCode != pCode)
                {
                    //UCGrid1.SetDataSource(pList);
                    btnView.Visible = true;
                    lblReportType.Visible = true;
                    drpDownReportType.Visible = true;
                    //CompareValidator2.Visible = true;
                }

            }
            else
            {
                btnView.Visible = false;
                UCGrid1.Visible = false;
                drpDownReportType.Visible = false;
                lblReportType.Visible = false;

                MassageSummery("IIS504");

            }
        }

        #region get item 4 selected radio button
        public void GetId(GridViewRow row)
        {
            //Session.Remove("quotationNum1");
            Session["quotationNum"] = row.Cells[2].Text;

            Session["planCode"] = row.Cells[5].Text;
            Session["soCode"] = row.Cells[3].Text;
            //lblResult.Visible = false;

            LoadDrpReport(Session["quotationNum"].ToString());

            //lblResult.Visible = false;
        }
        #endregion

        private void LoadDrpReport(string QuoNum)
        {
            StructureFacade fac = new StructureFacade();
            List<String> quotation = fac.GetLives(QuoNum);

            //ProspectQuotations orgQuotation = fac.GetQuotation(QuoNum);
            pCode = fac.GetQuotation(QuoNum).PlanCode;
            if (pCode == "PEN" || pCode == "80" || pCode == "81")
            {
                drpDownReportType.Items.Clear();
                //string planCode = fac.GetQuotation(QuoNum).PlanCode;
                btnView.Visible = true;
                lblReportType.Visible = false;
                drpDownReportType.Visible = false;
                plnCode = pCode;






                //Session.Remove("quotationNum");

            }
            else if (quotation.Count != 0)
            {
                
                lblReportType.Visible = true;
                drpDownReportType.Visible = true;
                //CompareValidator2.Visible = true;
                drpDownReportType.Enabled = true;
                btnView.Enabled = true;
                btnView.Visible = true;

                string str = "Select...";
                quotation.Insert(0, str);
                drpDownReportType.DataSource = quotation;
                drpDownReportType.DataBind();
                //Session.Remove("quotationNum");
            }
            else
            {
                drpDownReportType.Enabled = false;
                btnView.Enabled = false;
                MassageSummery("IIS504");
            }



        }

        protected void btnView_Click(object sender, EventArgs e)
        {
            //string reportType = drpDownReportType.SelectedValue;
            //string reportTypeName = drpDownReportType.SelectedItem.ToString();
            try
            {




                if (Session["quotationNum"] == null)
                {

                    Session["quotationNum"] = ((GridViewRow)Session["firstRow"]).Cells[2].Text;
                    Session.Remove("firstRow");
                }

                string planCode = fac.GetQuotation(Session["quotationNum"].ToString()).PlanCode;



                if (planCode == "PEN")
                {
                    string url = "../SalesQuotations/ViewReportPen.aspx?QuotationNum=" + Session["quotationNum"].ToString();
                    string fullURL = "window.open('" + url + "', '_blank', 'height=1000,width=1000,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
                    ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);
                }


                else if (planCode == "80")
                {
                    string url = "../SalesQuotations/ViewReport80.aspx?QuotationNum=" + Session["quotationNum"].ToString();
                    string fullURL = "window.open('" + url + "', '_blank', 'height=1000,width=1000,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
                    ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);

                }
                else if (planCode == "81")
                {
                    string url = "../SalesQuotations/ViewReport81.aspx?QuotationNum=" + Session["quotationNum"].ToString();
                    string fullURL = "window.open('" + url + "', '_blank', 'height=1000,width=1000,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
                    ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);

                }


                else if (drpDownReportType.SelectedIndex > 0)
                {
                    string reportType = drpDownReportType.SelectedValue;
                    string reportTypeName = drpDownReportType.SelectedItem.ToString();


                    if (Session["quotationNum"] == null)
                    {

                        Session["quotationNum"] = ((GridViewRow)Session["firstRow"]).Cells[2].Text;
                        Session["planCode"] = ((GridViewRow)Session["firstRow"]).Cells[5].Text;
                        Session.Remove("firstRow");
                    }




                    if (Session["quotationNum"] != null && Session["planCode"] != null && reportType != "0")
                    {
                        //string flag="";


                        string QuoNum = Session["quotationNum"].ToString();
                        //lblResult.Visible = false;
                        //string quoNum = Session["quotationNum"].ToString();
                        //string planCode = Session["planCode"].ToString();
                        //StructureFacade fac = new StructureFacade();
                        List<QuotationDetails> quotation = fac.GetQuotationsDetails(QuoNum);


                        if (reportType == "MNLIFE")
                        {
                            string url = "../SalesQuotations/ViewReportMNLife.aspx?Life=" + reportTypeName + "&QuotationNum=" + QuoNum;
                            string fullURL = "window.open('" + url + "', '_blank', 'height=1000,width=1000,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
                            ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);


                            //Response.Redirect("~/SalesQuotations/ViewReportMNLife.aspx?Life=" + reportTypeName + " &QuotationNum=" + QuoNum);

                        }
                        else if (reportType == "SPOUSE")
                        {

                            string url = "../SalesQuotations/ViewReportSpouse.aspx?Life=" + reportTypeName + " &QuotationNum=" + QuoNum;
                            string fullURL = "window.open('" + url + "', '_blank', 'height=1000,width=1000,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
                            ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);

                            //Response.Redirect("~/SalesQuotations/ViewReportSpouse.aspx?Life=" + reportTypeName + " &QuotationNum=" + QuoNum);

                        }
                        else if (reportType == "CHILD1")
                        {

                            string url = "../SalesQuotations/ViewReportChild1.aspx?Life=" + reportTypeName + " &QuotationNum=" + QuoNum;
                            string fullURL = "window.open('" + url + "', '_blank', 'height=1000,width=1000,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
                            ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);


                            //Response.Redirect("~/SalesQuotations/ViewReportChild1.aspx?Life=" + reportTypeName + " &QuotationNum=" + QuoNum);
                        }
                        else if (reportType == "CHILD2")
                        {
                            string url = "../SalesQuotations/ViewReportChild2.aspx?Life=" + reportTypeName + " &QuotationNum=" + QuoNum;
                            string fullURL = "window.open('" + url + "', '_blank', 'height=1000,width=1000,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
                            ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);



                            //Response.Redirect("~/SalesQuotations/ViewReportChild1.aspx?Life=" + reportTypeName);
                        }
                        else if (reportType == "CHILD3")
                        {

                            string url = "../SalesQuotations/ViewReportChild3.aspx?Life=" + reportTypeName + " &QuotationNum=" + QuoNum;
                            string fullURL = "window.open('" + url + "', '_blank', 'height=1000,width=1000,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
                            ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);


                            //Response.Redirect("~/SalesQuotations/ViewReportChild1.aspx?Life=" + reportTypeName);
                        }

                        else if (reportType == "CHILD4")
                        {

                            string url = "../SalesQuotations/ViewReportChild4.aspx?Life=" + reportTypeName + " &QuotationNum=" + QuoNum;
                            string fullURL = "window.open('" + url + "', '_blank', 'height=1000,width=1000,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
                            ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);


                            //Response.Redirect("~/SalesQuotations/ViewReportChild1.aspx?Life=" + reportTypeName);
                        }

                        else if (reportType == "CHILD5")
                        {

                            string url = "../SalesQuotations/ViewReportChild5.aspx?Life=" + reportTypeName + " &QuotationNum=" + QuoNum;
                            string fullURL = "window.open('" + url + "', '_blank', 'height=1000,width=1000,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,titlebar=no' );";
                            ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", fullURL, true);


                            //Response.Redirect("~/SalesQuotations/ViewReportChild1.aspx?Life=" + reportTypeName);
                        }



                    }
                    else
                    {
                        //lblResult.Visible = true;
                        //lblResult.Text = "Please select relavant fields to be viewed.";
                        //lblResult.ForeColor = System.Drawing.Color.Red;

                        MassageSummery("IIS505");

                    }
                }
                else if (drpDownReportType.SelectedIndex <= 0)
                {
                    MassageSummery("IIS505");
                }
            }catch (Exception ex){}
               

        }

        #region IDataPage Members

        public void Create()
        {

        }

        public void View()
        {

        }

        public void Update()
        {

            //Response.Redirect("/Messaging/UpdateMessage.aspx?a=19");
        }

        public void Delete()
        {

        }

        public void Cancel()
        {

        }

        #endregion



        #region IntTest Members

        public void Next()
        {
            SOCode = drpSOCode.SelectedValue.ToString();
            DateFrom = Convert.ToDateTime(txtFromDate.Text);
            DateTo = Convert.ToDateTime(txtToDate.Text);

            if (UCGrid1.GetText() != "1")
            {
                pageNo = Convert.ToInt32(UCGrid1.GetText()) + 1;
                UCGrid1.SetText(pageNo.ToString());
                SearchQuotations(SOCode, DateFrom, DateTo, pageNo);
                

                LoadGrid(quoList);

            }
            else
            {
                pageNo = 2;
                UCGrid1.SetText("2");
                SearchQuotations(SOCode, DateFrom, DateTo, pageNo);
                LoadGrid(quoList);

            }

            
        }

        public void Previous()
        {
            SOCode = drpSOCode.SelectedValue.ToString();
            DateFrom = Convert.ToDateTime(txtFromDate.Text);
            DateTo = Convert.ToDateTime(txtToDate.Text);

            if (UCGrid1.GetText() != "1")
            {
                pageNo = Convert.ToInt32(UCGrid1.GetText()) - 1;
                UCGrid1.SetText(pageNo.ToString());

                SearchQuotations(SOCode, DateFrom, DateTo, pageNo);
                LoadGrid(quoList);
            }
        }

        public void Go()
        {
            int p = int.Parse(UCGrid1.GetText());
            SOCode = drpSOCode.SelectedValue.ToString();
            DateFrom = Convert.ToDateTime(txtFromDate.Text);
            DateTo = Convert.ToDateTime(txtToDate.Text);
            if (p != 0)
            {
                try
                {
                    SearchQuotations(SOCode, DateFrom, DateTo, p);
                    LoadGrid(quoList);

                    pageNo = p;
                }
                catch (Exception)
                {

                    throw;
                }


            }
        }

        #endregion
    }
}
